package user_api

import (
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/ctype"
	"ginBolg/models/res"
	"ginBolg/plugins/qq"
	"ginBolg/utils"
	"ginBolg/utils/jwt"
	"ginBolg/utils/random"
	"github.com/gin-gonic/gin"
)

func (UserApi) QQLoginView(c *gin.Context) {
	code := c.Query("code")
	if code == "" {
		res.Fail("code不存在", c)
		return
	}
	qqInfo, err := qq.NewQQLogin(code)
	if err != nil {
		res.Fail(err.Error(), c)
		return
	}
	openID := qqInfo.OpenID
	var user models.UserModel
	err = global.DB.Take(&user, "token = ?", openID).Error
	if err != nil {
		// 不存在就注册
		hashPwd := utils.HashAndSalt(random.RandStr(16))
		user = models.UserModel{
			NickName:   qqInfo.NickName,
			UserName:   openID,
			Password:   hashPwd, // 随机生成
			Avatar:     qqInfo.Avatar,
			Addr:       "",
			Token:      openID,
			IP:         c.ClientIP(),
			Role:       ctype.PermissionUser,
			SignStatus: ctype.SignQQ,
		}
		err = global.DB.Create(&user).Error
		if err != nil {
			global.Log.Error(err)
			res.Fail("注册失败", c)
			return
		}
	}
	// 登录操作
	token, err := jwt.GenToken(jwt.JwtPayLoad{
		NickName: user.NickName,
		Role:     int(user.Role),
		UserId:   user.ID,
	})
	if err != nil {
		global.Log.Error(err)
		res.Fail("token 生成失败", c)
		return
	}
	res.OkWithData(token, c)
}
